package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    JwtTokenProperties jwtTokenProperties;

    @Override
    public LoginVo login(LoginDto dto) {

        User user = userMapper.selectByUsername(dto.getUsername());
        if (ObjectUtil.isEmpty(user)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //判断用户是否被禁用
        if (user.getDataState().equals(SuperConstant.DATA_STATE_1)) {
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        //判断密码是否正确
        if (!BCrypt.checkpw(dto.getPassword(), user.getPassword())) {
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        LoginVo userVo = BeanUtil.toBean(user, LoginVo.class);

        /*密码脱敏*/
        userVo.setPassword(" ");

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userVo.getId());

        String token = JwtUtil.createJWT(jwtTokenProperties.getSecretKey(),
                jwtTokenProperties.getTtl(), claims);
        userVo.setUserToken(token);
        return userVo;
    }
}
